import {
  ConflictException,
  Injectable,
  InternalServerErrorException,
  UnauthorizedException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
import { User } from './user.entity';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { JWTPayload } from './jwt-payload.interface';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(User)
    private readonly usersRepository: Repository<User>,
    private readonly jwtService: JwtService,
  ) {}

  /**
   * 新建
   */
  async signUp(authCredentialsDto: AuthCredentialsDto): Promise<boolean> {
    try {
      const { username, password } = authCredentialsDto;
      // hash
      const salt = await bcrypt.genSalt();
      const hashedPassword = await bcrypt.hash(password, salt);
      console.log('signup', salt, hashedPassword);
      const user = this.usersRepository.create({
        username,
        password: hashedPassword,
      });
      await this.usersRepository.save(user);
      return true;
    } catch (error) {
      if (error.code == 23505) {
        throw new ConflictException('名字已存在');
      } else {
        throw new InternalServerErrorException();
      }
    }
  }

  async signIn(
    authCredentialsDto: AuthCredentialsDto,
  ): Promise<{ accessToken: string }> {
    const { username, password } = authCredentialsDto;
    const user = await this.usersRepository.findOne({ where: { username } });
    console.log('signIn', user);
    if (user && (await bcrypt.compare(password, user.password))) {
      // 登录
      const payload: JWTPayload = { username };
      const accessToken = await this.jwtService.sign(payload);
      return { accessToken };
    }

    throw new UnauthorizedException('请检查登录信息');
  }
}
